var liveIM = require('../../utils/live-im');
var TIM = require('../../miniprogram_npm/tim-wx-sdk/index');
var COS = require('../../miniprogram_npm/cos-wx-sdk-v5/index');
var utils = require("../../utils/utils");
var app = getApp();

let timer=null
let timer2=null;
const createRecycleContext = require('miniprogram-recycle-view')
const rpx2px = (rpx) => (rpx / 750) * wx.getSystemInfoSync().windowWidth
var recycleView = ''
Page({
  data: {
    c_app:app,
    statusBarHeight:0,
    zanStart:0,
    height:0,
    customerId:false, //获取手机号
    showKeyboard:true,
    showInput:false,
    showGoods:false,
    showCard:false,
    showModal:false,
    liveData:{
      connect_pull_url:'', //连麦
      connect_status:'0'
    },
    kefu:{
      yes:false,
      img:'',
      name:''
    },
    replyTxt:'',
    txtMsg:'',
    txtMsgList:[],
    txtMsgStop:false,
    zanCount:0,
    lookCount:0,
    goodsList:[],
    cradList:[],
    liveStart:false,
    showGoodsTip:false,
    goodsTipIdx:-1,
    goodsMoneyTipList:[],
    goodsCountTipList:[],
    lotteryStatus:0,
    showLottery:false,
    lotteryList:[], // 抽奖列表
    lotteryItem:{}, // 当前抽奖
    lotteryStatus:0, // 抽奖状态
    uuidYes:'', // 当前自己中奖口令
    lotteryHistory:[], // 中奖列表
    showLotteryHistory:false,
    showContrast:false,
    contrastTip:{},
    showContrastTip:false,
    contrastGoodsIdx:-1,
    newLiveUrl:'',
    liveType:0,
    subscribe:0,  //0,1
    noMsg:[],
    HB:{ // 红包
      id:'0', show:false,time:10
    },
    showQA:'',
    listQA:[],
    indexQA:0,
    timeQA:10,
    timeOutQA:null,
    rewardQA:false, //是否答题结束
    getQA:false, //是否有奖励
    QAnumaward:-2, //是否有奖励且库存充足
    replyName:'',  // LCL 回复昵称
    sign_status:0,  // LCL 签到状态
    enter_mode:1,   //LCL 直播间模式：1.所有都可进入，2.付费模式，3.邀请码模式，4.白名单模式
    live_goods_id:0,  //LCL 付费模式商品ID
    live_goods_price:0,  //LCL 付费模式价格
    txtPwds:'',  //LCL 邀请码模式：密码
    enter_msg:'',  //LCL 特定直播间描述
    substatus:1,   //LCL 订阅通知显示
    notRefresh: false, // 不允许刷新
    linkman: '', // 自提联系人
    phone: '', // 自提联系电话
    disabled: false,   // 禁用submit按钮
    showCheckin:false,   // 签到弹出
    showRule:false,   // 签到规则弹出
    checkin_my_status:0,   // 自己签到的状态
    checkin_share_status:0,   // 朋友签到的是否可领奖状态  不用了，后台返回
    signup_mode:1,   //签到模式，1：正常模式，2：奖励模式
    signData:{},    //签到信息
    shareData:[],   //签到好友列表
    is_phone: 0,   //0=未启动授权手机，1=已启动授权手机
    load_e: '',
    scrollTop: 0,  //虚拟列表聊天室滚动的位置
    recycleViewWidth: 360,  //默认聊天室虚拟列表宽度
    recycleViewHeight: 240, //默认聊天室虚拟列表高度
    isEnableScroll: true, //是否能够滚动到底
    timerEnd: '',  //滚动结束
    hiddenMoreInfo: true,  //是否隐藏更多信息
    moreInfoLength: 0,  //聊天室更多信息
    initNumber: 0, //是否是第一次onShow页面
    totalZanNumber: 0, //收集一段时间内的总点赞数量
    maxRecycleViewLength: 60,
    referee_push_hb_disable: false, //防止重复点击领取红包，
    isShowHongBao: false, //是否显示红包组件
    HongBaoCount: 0, //待领取的红包个数
    showHbModal:false, //显示红包列表弹窗
    hbId_arr : [], //红包id数组
    isShowCountdown: false, //是否显示倒计时组件
    countdown_extension:'',
    countdown_time:0,
    // 滚动公告
    // marqueePace: 1,//滚动速度
    // marqueeDistance: 0,//初始滚动距离
    // noticesize: 26,
    // noticeinterval: 20, // 时间间隔
    // noticeShow:false
  },

  /**
   * 生命周期函数
   */
  onLoad: function (e) {
    let t = this,scene = app.helper.scene_decode(decodeURIComponent(t.scene))
    e.id = e.id ? e.id : scene.id;
    t.setData({
      load_e: e
    })
  },
  onReady: function () {
    let t = this;
    t.createRecycleView()
  },
  onShow: function () {
    let t = this, token = wx.getStorageSync('ACCESS_TOKEN');
    app.page.onLoad(t, t.data.load_e)
    if(token){
      // app.page.checkBinding()
      this.data.initNumber == 0 && t.setInitPage(t, t.data.load_e, token);
    }
    this.data.initNumber = this.data.initNumber + 1;
    this.inviteShare('onShow')
  },
  onHide: function () {
    this.setData({
      showGoods:false,
      showModal:false,
      HongBaoCount:0
    })
    this.inviteShare('onHide')
  },
  onUnload: function () {
    timer && clearTimeout(timer);
    liveIM.tim && liveIM.kill();
    clearTimeout(this.data.timeOutQA);
    this.inviteShare('onUnload')
    this.setData({HongBaoCount:0 })
  },
  /**
   * 生命周期函数end
   */
  createRecycleView() {
    var _this = this
    recycleView = createRecycleContext({
        id: 'recycleId',
        dataKey: 'recycleList',
        page: this,
        itemSize: {
            height: rpx2px(50),
            width: rpx2px(660)
        }
    })
  },

  
  scrollBottom() {
    let _this = this
    console.log('recycleView',recycleView)
    let recycleViewLength = recycleView.comp===null?0:recycleView.comp.sizeArray.length
    if (!_this.data.isEnableScroll) {
        // console.log('不能到底')
        return
    }
    // console.log('能到底')
    _this.setData({
        scrollTop: recycleViewLength * 1000
    })
  },
  //滚动触发
  bindscroll: utils.debounce(function (args) {
    let _this = this
    let e = args[0]
    // console.log('滚动位置',e.detail.scrollTop,'总长度',recycleView.comp.totalHeight)
    const scrollTop = e.detail.scrollTop
    const totalHeight = recycleView.comp.totalHeight
    if (totalHeight - scrollTop >= _this.data.recycleViewHeight) {
        _this.setData({
            hiddenMoreInfo: false
        })
    } else {
        _this.setData({
            hiddenMoreInfo: true
        })
    }
  }),
  binddragstart() {
    console.log('滑动开始')
    this.data.isEnableScroll = false
    clearTimeout(this.data.timerEnd)
  },
  bindscrolltolower() {
    let _this = this
    // console.log('到底了')
    _this.data.timerEnd = setTimeout(() => {
        _this.setData({
            isEnableScroll: true,
            hiddenMoreInfo: true,
            // moreInfoLength :0
        })
    }, 700)
  },
  bindscrolltoupper() {
    this.setData({
        scrollTop: 25
    })
  },
  clickMoreInfo() {
    this.data.isEnableScroll = true
    this.scrollBottom()
  },
  recycleViewAppendList(list) {
    let _this = this
    console.log('recycleView2',recycleView)
    let recycleViewLength = recycleView.comp===null?0:recycleView.comp.sizeArray.length
    if (Object.prototype.toString.call(list) == '[object Object]') {
        //console.log('list是对象')
        list = [list]
    }
    //查看更多信息
    // if(!this.data.hiddenMoreInfo){
    //   this.setData({
    //     moreInfoLength :this.data.moreInfoLength+list.length > (_this.data.maxRecycleViewLength-10) ? list.length : this.data.moreInfoLength+list.length
    //   })
    // }else{
    //   this.setData({
    //     moreInfoLength : 0
    //   })
    // }
    if ((list.length && (list.length + recycleViewLength)) > _this.data.maxRecycleViewLength) {
        recycleView.splice(0, list.length)
        recycleView.append(list)
    } else {
        recycleView.append(list)
    }
  },

  setInitPage(t,e,token){
    console.log(wx.getStorageSync('USER_INFO'))
    wx.getSystemInfo({
      success: (res) => {
        t.setData({
          statusBarHeight:res.statusBarHeight,
          token:token,
          parmas:e,
          options:e,
          _api_live: app.api.siteinfo.apiroot,
          userInfo:wx.getStorageSync('USER_INFO'),
        },function () {
          t.data.kefu={yes:false, name:t.data.userInfo.nickname, img:t.data.userInfo.avatar_url}
          t.getLiveCheck(t,e,token);
        })
      },
    });
  },
  //获取直播间验证信息
  getLiveCheck(t,e,token){
    var d = t.data;
    app.request({
      url: d._api_live + 'live/checkRoomEnter',
      data:{
        hosId: app.api.siteinfo.hosId2,
        access_token:token,
        liveId:e.id
      },
      success(res){
        if (res.need_phone == 1 && d.is_phone == 0) {
          wx.navigateTo({
            url: '/pages/phone/index',
          })
        } 
        if(res.is_ok == 1){
          t.setData({
            enter_mode:1,
            substatus:1,
            showInput:true,
            sign_status:0,
            live_goods_price:0,
            live_goods_id:0,
          })
          t.getLiveData(t,e,token);
          t.getCradList();
          t.getGoodsList();
        }else{
          t.setData({
            liveData:res,
            enter_msg:res.enter_msg,
            live_goods_price:res.goods_price,
            live_goods_id:res.enter_goods_id,
            substatus:0,
            enter_mode:res.enter_mode,
            showInput:false,
            sign_status:1,
          })
        }
      }
    })
  },
  /**
   * 判断邀约权限
   */
  inviteShare(action) {
    const _this = this, d = this.data
    const openId = wx.getStorageSync('ACCESS_TOKEN')
    app.request({
        url: _this.data._api_live + "inviteShare/notify",
        data: {
            hosId: app.api.siteinfo.hosId2,
            openId: openId,
            action: action,
            userId: d.userInfo.id,
            liveId: d.options.id
        },
        success(res) {
            console.log('判断邀约权限', res.data)
        }
    })
  },
  setInitIM(t,token,roomInfo){
    const configIM = {
      options:{SDKAppID:app.api.siteinfo.SDKAppID},
      setLogLevel:1,
      user:{
        userID: token,
        userSig: roomInfo.usersig
      },
      //群
      group:{ groupID: roomInfo.im_group_id, type: TIM.TYPES.GRP_AVCHATROOM },
      // 接受所有群消息
      message_received:t.getImMsg,
      error(e){console.log(e)}
    }
    liveIM.init(configIM,TIM,COS,t);
  },
  getLiveData(t,e,token){
    var d = t.data;
    //let starTime = new Date().getTime();
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/getRoomInfo',
      data:{
        hosId: app.api.siteinfo.hosId2,
        userId:token,
        liveId:e.id,
        oriToken:e.oriToken || '',
        referee_id:wx.getStorageSync('PARENT_ID')
      },
      success(res){
        // live_status 1:直播中，2：已结束，3：未开始
        if(res.result == 0) {
          if(res.staffList.length){
            res.staffList.forEach(item=>{
              if(item.access_token == token){
                t.data.kefu={yes:true, name:item.nickname, img:app.api.siteinfo.logo}
              }
            })
          }
          if(res.live_status != 1) {
            wx.removeStorageSync('noticeShow')
            t.setData({noticeShow:false})
          }else{
            t.setData({noticeShow:true})
          }
          // 加载历史消息
          if(res.history_msg.length){
            d.txtMsgList = res.history_msg
            t.recycleViewAppendList(res.history_msg)
          }
          const user = {
              img: app.api.siteinfo.logo, name: '欢迎', token: '',
              txt: d.userInfo.nickname + ' 进入直播间',
              yes: false, admin: false
          }
          t.recycleViewAppendList([user])
          if(res.countdown.length>0 && res.countdown[0].countdown_time_long>3){
            t.setData({
                isShowCountdown : true,
                countdown_extension:res.countdown[0],
                countdown_time:res.countdown[0].countdown_time_long
            })
          }
          t.setData({
            liveData:res,
            liveStart:res.live_status == 1?true:false,
            lookCount:res.look_num || 0,
            zanCount:res.zan_num || 0,
            kefu:t.data.kefu,
            //txtMsgList:d.txtMsgList,
            subscribe:res.subscribe,
            tplID:res.tplID,
            newLiveUrl:res.pull_url,
            liveType:res.liveType,
            signup_mode:res.signup_mode,
            noticelength:res.tips?res.tips.length * t.data.noticesize:0
          },function () {
            t.setInitIM(t,token,res);
            t.setLotteryList(res.lotteryData)
            //t.scrollNotice()
          })
        }
      }
    })
  },
  getGoodsList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/getGoodsList',
      data:{
        hosId:app.api.siteinfo.hosId2,
        liveId:d.parmas.id
      },
      success(e){
        e.data.length && t.setData({goodsList:e.data})
      }
    })
  },
  //卡券列表
  getCradList(){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/couponBatchList',
      data:{
        storeId:app.api.siteinfo.acid,
        liveId:d.parmas.id
      },
      success(e){
        e.data.length && t.setData({cradList:e.data})
      }
    })
  },
  getImMsg(e){
    // console.log('普通消息',e.data)
    let t = this;
    e.data.forEach(item=>{
      switch(item.type) {
        case 'TIMTextElem':
          t.getTextMsg(item,t)
          break;
        case "TIMCustomElem":
          t.getCustomMsg(item,t)
          break;
        default:
          console.log('未定义类型',item)
      }
    })
  },
  getTextMsg(e,t){
    let txt = JSON.parse(e.payload.text)
    this.recycleViewAppendList([txt])
    this.scrollBottom()
  },
  getCustomMsg(e,t){
    switch(e.payload.data) {
      case 'pushZan':
        //console.log('点赞量')
        t.setData({
          zanCount:t.data.zanCount+(e.payload.extension-0)
        })
        break;
      case "pushLook":
        //console.log('观看量')
        t.setData({
          lookCount:t.data.lookCount+(e.payload.extension-0)
        })
        break;
      case "pullPlay":
        //console.log('开播');
        t.setData({liveStart:true})
        break;
      case "pullGoods":
        //console.log('商品推送');
        let id, ex = JSON.parse(e.payload.extension);
        id = ex?ex.goodsId:'';
        t.setGoodsTip(id,t);
        break;
      case "pushMoney":
        //console.log('购买');
        t.setMoneyTip(e.payload.extension)
        break;
      case "pushWXGoodsTips":
        //console.log('商品剩余');
        t.setGoodsCountTip(e.payload.extension)
        break;
      case "updateGoods":
        //console.log('更新商品');
        t.getGoodsList(t,t.data.parmas.id)
        break;
      case "beginLottery":
        //console.log('开始抽奖',e.payload);
        t.startLottery(e.payload.extension)
        break;
      case "pullLottery":
        //console.log('已开奖',e.payload);
        t.endLotter(e.payload.extension)
        break;
      case "pullGoodsImg":
        //console.log('对比图',e.payload.extension);
        t.setContrastTip(t,e.payload.extension)
        t.setContrast()
        break;
      case "pullCoupon":
        //console.log('优惠券',e.payload.extension);
        var data = JSON.parse(e.payload.extension)
        t.setCradTip(t,data.couponId)
        break;
      case "pullUrl":
        //console.log('切换镜头',e.payload);
        let ext = JSON.parse(e.payload.extension)
        t.setData({
          newLiveUrl:ext.url,
          liveType:ext.type,
          liveStart:true
        })
        break;
      case "pullCoupon":
        //console.log('优惠券',e.payload.extension);
        break;
      case "pullHB":
        //console.log('红包',e.payload.extension);
        t.setHB(JSON.parse(e.payload.extension))
        break;
      case "pushWXQA":
        //console.log('问答',e.payload.extension);
        t.setQATime(JSON.parse(e.payload.extension))
        break;
      case "pushgoodIdWant":
        //console.log('想要',e.payload.extension);
        t.setWant(JSON.parse(e.payload.extension))
        break;
      case "pushConnectUrl":
        //console.log('连麦',e.payload.extension);
        let o = JSON.parse(e.payload.extension);
        t.setData({
          'liveData.connect_status':o.status,
          'liveData.connect_pull_url':o.connect_url
        })
        break;
      case "inviteHB":
        //console.log('邀约结果',e.payload.extension);
        let extension = JSON.parse(e.payload.extension);
        const openid = wx.getStorageSync('ACCESS_TOKEN')
        const user_id = t.data.userInfo.id
        if(extension.referee_open_id==openid||extension.referee_id==user_id){
            t.data.hbId_arr.push(extension.hbId)
            t.setData({
                isShowHongBao : true,
                HongBaoCount:t.data.HongBaoCount +1,
                hbId_arr:t.data.hbId_arr
            })
        }
        break;
      case "countdownTips":
        //console.log('倒计时',e.payload.extension);
        let countdown_extension = JSON.parse(e.payload.extension);
        t.setData({ isShowCountdown : false})
        setTimeout(()=>{
            t.setData({
                isShowCountdown : true,
                countdown_extension:countdown_extension,
                countdown_time:countdown_extension.countdown
            })
        },0)
        break;
      default:
        console.log('未定义类型',e)
    }
  },

  //跳转我的优惠券
  setlookcoupon(){
    console.log('setlookcoupon')
    // wx.navigateTo({
    //   url: '/pages/user/coupon/list/index?currentTab=1',
    // })
  },
  navigateBack(){
    wx.navigateBack({
      delta: 1,
      success(){
        console.log('success')
      },
      fail(){
        wx.redirectTo({
          url: '/cheng/pages/live-list/live-list'
        })
      }
    })
  },
  setZanCount() {
    let _this = this;
    // console.log('点赞+1')
    _this.data.totalZanNumber = _this.data.totalZanNumber + 1
    _this.setData({
        showZan: true,
        zanStart: _this.data.zanStart + 1,
        zanCount: _this.data.zanCount + 1
    });
    // let message = liveIM.tim.createCustomMessage({
    //     to: liveIM.config.group.groupID,
    //     conversationType: TIM.TYPES.CONV_GROUP,
    //     payload: {
    //       data: 'pushZan',
    //       description: '点赞+1',
    //       extension: '1'
    //     }
    //   });
    //   liveIM.tim.sendMessage(message);
    if (timer2) clearTimeout(timer2);
    timer2 = setTimeout(function () {
        console.log('停止点赞后触发,点赞总数量', _this.data.totalZanNumber)
        let message = liveIM.tim.createCustomMessage({
            to: liveIM.config.group.groupID,
            conversationType: TIM.TYPES.CONV_GROUP,
            payload: {
                data: 'pushZan',
                description: '点赞+1',
                extension: `${_this.data.totalZanNumber}`
            }
        });
        liveIM.tim.sendMessage(message);
        _this.setData({
            showZan: false,
            totalZanNumber: 0
        })
    }, 4000)
  },

  setPushTxtMsg(txt){
    let d = this.data,kefu=d.kefu;
    let txtMsg = {img:kefu.img, name:kefu.name, token:d.token, txt:txt, yes:kefu.yes, replyTxt:d.replyTxt};

    let message = liveIM.tim.createTextMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {text:JSON.stringify(txtMsg)}
    })
    liveIM.tim.sendMessage(message);
    return txtMsg;
  },
  setGoodsTip(id,t){
    if(!id) return;
    if(timer) clearTimeout(timer);
    t.data.goodsList.forEach((item,idx)=>{
      item.id == id && t.setData({
        showGoodsTip:true,
        goodsTipIdx:idx,
        showContrastTip:false,
        showCradTip:false,
        showContrast:false
      },function () {
        timer = setTimeout(function () {
          t.setData({showGoodsTip:false})
        },60*1000)
      })
    })
  },

  setGoodsCountTip(obj){
    let o = JSON.parse(obj);
    if(o.count - 0 > 10) return;
    let l = this.data.goodsCountTipList;
    let item = this.data.goodsList.find(i=>i.id == o.goodsId);
    item.count = o.count;l.push(item);
    this.setData({goodsCountTipList:l});
  },
  setMoneyTip: utils.throttle(function (obj) {
    let o = JSON.parse(obj);
    let l = this.data.goodsMoneyTipList;
    l.length > 10 && l.splice(0, 5)
    l.push(o)
    this.setData({goodsMoneyTipList: l})
  }, 2800, false),
  setContrastTip(t,d){
    let data = JSON.parse(d)
    if(timer) clearTimeout(timer);
    t.data.goodsList.forEach((item,idx)=>{
      item.id == data.goodsId && t.setData({
        showContrastTip:true,
        contrastTip:data,
        contrastGoodsIdx:idx,
        showGoodsTip:false
      },function () {
        timer = setTimeout(function () {
          t.setData({showContrastTip:false,showContrast:false})
        },60*1000)
      })
    })
  },
  //优惠券推送
  setCradTip(t,id){
    if(timer) clearTimeout(timer);
    t.data.cradList.forEach((item,idx)=>{
      item.coupon_batch_id == id && t.setData({
        showCradTip:true,
        tipIdx:idx,
        showGoodsTip:false,
        showContrastTip:false,
        showContrast:false
      },function () {
        timer = setTimeout(function () {
          t.setData({showCradTip:false})
        },60*1000)
      })
    })
  },
  setInput(e,replyName,replyTxt) {
    this.setData({showInput: true,txtMsg:'',replyTxt:replyTxt,replyName:'回复：'+replyName}) 
  },
  delInput(){this.setData({showInput: true, height:0})},
  inputText(e){this.setData({txtMsg:e.detail.value})},
  inputSubmit: utils.throttle(function () {
    let t = this, d = t.data;
    if (!d.txtMsg) return;
    let l = d.txtMsgList;
    let txt = t.setPushTxtMsg(d.txtMsg);
    t.recycleViewAppendList([txt])
    t.scrollBottom()
    this.setData({
        // txtMsgList:l,
        txtMsg: '',
        replyTxt: '',
        replyName: ''
    }, function () {
        d.txtMsgStop = true
        setTimeout(function () {
            d.txtMsgStop = false
        }, 500)
    })
  }),
  setHeight(e){this.setData({height:e.detail.height || 0})},
  setGoods(){this.setData({showGoods:true})},
  delGoods(){this.setData({showGoods:false})},
  setCard(){this.setData({showCard:true})},
  delCard(){this.setData({showCard:false})},
  goGoods(ele){
    let item = ele.currentTarget.dataset.item;
    if(item && item.want_type == 1) {this.want(item);return}
    let d = this.data;
    let user = {
      name:d.userInfo.nickname.substring(0,2)+'**',
      img:d.userInfo.avatar_url,
    }
    let message = liveIM.tim.createCustomMessage({
      to: liveIM.config.group.groupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        data: 'pushMoney',
        description: '正在购买',
        extension: JSON.stringify(user)
      }
    });
    liveIM.tim.sendMessage(message);
    console.log("usl",ele)
    wx.navigateTo({url:ele.currentTarget.dataset.url})
  },
  //想要
  want(item){
    let t = this,d=t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/wantgood',
      data:{
        storeId:app.api.siteinfo.acid,
        liveId:d.parmas.id,
        access_token:d.token,
        good_id:item.id
      }
    })

  },
  setWant(obj){
    let t = this,d=t.data;
    let idx = d.goodsList.findIndex(i=>i.id==obj.goodsId);
    d.goodsList[idx].want_price = obj.want_price;
    d.goodsList[idx].want_count = obj.want_count;
    d.goodsList[idx].want_type = obj.want_type;
    this.setData({goodsList:d.goodsList})
  },
  //领取卡券
  getCard(e){
    var idx = e.currentTarget.dataset.idx,
      toast = e.currentTarget.dataset.toast,
      t = this, d = t.data, card = d.cradList[idx];
    if(card.is_over || card.status) return;
    var appUserInfo = wx.getStorageSync('appUserInfo');
    if(appUserInfo && appUserInfo.customerId){
      app.request({
        url:getApp().api.siteinfo.apiroot+'live/grantCouponId',
        data:{
          storeId:app.api.siteinfo.acid,
          liveId:d.parmas.id,
          couponBatchId:card.coupon_batch_id,
          mobile:appUserInfo.mobile,
          customerId:appUserInfo.customerId,
          access_token:d.token
        },
        success(e){
          var tip = e.data.is_over?'已领完':(e.data.status?'领取成功':'领取失败')
          wx.showToast({title:tip,icon:'none'})
          e.data.coupon_name = e.data.couponBatchName;
          e.data.coupon_batch_id = e.data.couponBatchId;
          d.cradList[idx] = e.data
          t.setData({cradList:d.cradList})
        }
      })
    }else {
      t.setData({customerId:true})
    }
  },

  setModal(){this.setData({showModal:true})},
  delModal(){this.setData({showModal:false})},
  setContrast(){this.setData({showContrast:true})},
  delContrast(){this.setData({showContrast:false})},

  // 所有抽奖信息
  setLotteryList(lotteryData){
    let t = this,d=t.data,item=null,list=null;
    list = lotteryData.filter((m,i)=>{
      if(m.lotteryStatus==1) item=m;
      return m.lotteryStatus>0;
    });
    if(list.length<1) return;
    item || (item = list[list.length-1])
    //item.recordList.forEach(i=>{i.nickname = i.nickname.substring(0,2)+'**'})
    item.recordList.forEach(i=>{i.nickName = i.nickName})
    this.setData({
      lotteryItem:item,
      lotteryStatus:item.lotteryStatus,
      lotteryList:list
    })
  },
  startLottery(ext){
    let t = this,d = t.data;
    let ex = JSON.parse(ext),idx = -1;

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0){
      d.lotteryList[idx] = ex;
    }else {
      d.lotteryList.push(ex)
    }
    // 开始抽奖
    t.setData({
      lotteryStatus:1,
      lotteryItem:ex,
      lotteryList:d.lotteryList,
      uuidYes:'',
      uuidCoupon:''
    })
  },
  endLotter(ext){
    let t = this,d = t.data;
    // 中奖
    let ex = JSON.parse(ext),idx = -1;
    let lotteryItem,uuidYes='',uuidCoupon='';

    d.lotteryList.forEach((item,idx)=>{
      if(item.lotteryId == ex.lotteryId) idx = idx;
    })
    if(idx >= 0){
      d.lotteryList[idx] = ex;
    }else {
      d.lotteryList.push(ex)
    }

    ex.recordList.forEach(item=>{
      //item.nickname = item.nickname.substring(0,2)+'**'
      item.nickName = item.nickName
      if(item.token == d.token){
        uuidYes = item.uuId
        uuidCoupon = item.coupon_name
      }
    })
    t.setData({
      lotteryList:d.lotteryList,
      lotteryItem:ex,
      uuidYes,
      uuidCoupon,
      lotteryStatus:2,
      showInput:false,
      showContrast:false,
      showGoods:false,
      showModal:false,
      showLotteryHistory:false,
      showLottery:true
    })
  },
  // 中奖记录
  setLotteryHistory(){
    let t = this,d = t.data;
    let lotteryHistory = [];
    d.lotteryList.forEach(item=>{
      item.recordList.forEach(l=>{
        l.lotteryName = item.lotteryName
        lotteryHistory.push(l)
      })
    })
    t.setData({
      lotteryHistory,
      showLotteryHistory:true
    })
  },
  setShowLottery(){this.setData({showLottery:true})},
  delLottery(){
    this.setData({
      showLottery:false,
      showLotteryHistory:false
    })
  },
  //点击自动发送评论参与抽奖
  msgLottery: utils.throttle(function () {
    let t = this, d = t.data;
    // lotteryType 1:评论，2：购买
    if (d.lotteryItem.lotteryType == '1') {
        let l = d.txtMsgList;
        let txt = t.setPushTxtMsg(d.lotteryItem.lottery_content);
        // l.push(txt)
        t.recycleViewAppendList([txt])
        t.scrollBottom()
        this.setData({
            // txtMsgList:l,
            txtMsg: '',
            replyTxt: '',
            replyName: '',
            showLottery: false,
            showLotteryHistory: false
        }, function () {
            d.txtMsgStop = true
            setTimeout(function () {
                d.txtMsgStop = false
            }, 500)
        })
        wx.showToast({icon: 'none', title: '参与成功'})
    } else {
        const txt = {
            img: d.userInfo.avatar_url,
            name: d.userInfo.nickname,
            txt: '参与购买成功！',
        }
        t.recycleViewAppendList([txt])
        t.scrollBottom()
        this.setData({
            // showGoods: true,
            showLottery: false,
            showLotteryHistory: false
        })
        wx.showToast({icon: 'none', title: '参与成功'})
    }
  }),
  setCopy(e){
    wx.setClipboardData({
      data:e.currentTarget.dataset.uuid
    })
  },
  //订阅
  setSubscribe(){
    let t = this,d = t.data
    if(d.liveData.live_status != 3 || d.subscribe) return;
    wx.requestSubscribeMessage({
      tmplIds:d.tplID,
      success(e){
        JSON.stringify(e).indexOf('accept')>0 && t.pushSubscribe()
      }
    })
  },
  pushSubscribe(){
    let t = this,d = t.data;
    app.request({
      url:getApp().api.siteinfo.apiroot+'live/subscribeLive',
      data:{
        hosId: app.api.siteinfo.hosId2,
        userId:d.token,
        liveId:d.liveData.live_id
      },
      success(e){
        wx.showToast({title:'订阅成功',icon:'none'})
        t.setData({subscribe:1})
      }
    })
  },
  reply(e){ //回复消息
    let t = this,d=t.data,item=e.currentTarget.dataset.item;
    if(!d.kefu.yes || item.yes) return;
    t.setInput({},item.name+': '+item.txt);
  },
  setNoMsg(e){
    let t = this,d=t.data,item=e.currentTarget.dataset.item;
    if(!d.kefu.yes || item.yes) return;
    d.noMsg.push({
      text:'禁言: '+item.name,
      value:item.token
    });
    t.setData({noMsg:d.noMsg})
  },
  getNoMsg(e){
    let d = this.data;
    this.setData({noMsg:[]})
    if(e.type == 'actiontap'){
      app.request({
        url:getApp().api.siteinfo.apiroot+'live/forbidSendMsg',
        data:{
          hosId: app.api.siteinfo.hosId2,
          userID: e.detail.value,
          liveId: d.parmas.id
        },
        success(){wx.showToast({title:'禁言成功',icon:'none'})}
      })
    }

  },

  // 红包
  setHB(obj){
    this.setData({HB:{id:obj.hb_batch_id, time:obj.time, show:true}})
  },
  getHB(c){
    this.setData({'HB.show':false})
    let d = this.data,hb = d.HB;
    if(!c.detail) return;
    wx.navigateTo({
      url:'/cheng/pages/money/money?id='+hb.id+'&count='+c.detail+'&liveId='+d.options.id
    })
  },

  // 问答
  setQATime(obj){
    this.setData({
      showQA:obj.reward,
      listQA:obj.data.map(i=>{
        i.select = [{v:i.answer_1,bg:''},{v:i.answer_2,bg:''},{v:i.answer_3,bg:''},{v:i.answer_4,bg:''}];
        return i
      }),
      rewardQA:false,
      getQA:false,
      indexQA:0,
      timeQA:10,
      timeOutQA:null,
    },this.startQA)
  },

  startQA(){
    let t = this,d=t.data;
    d.timeOutQA = setInterval(()=>{
      if(d.timeQA>0){
        t.setData({timeQA:--d.timeQA})
      }else if(d.listQA.length-1>d.indexQA && d.listQA[d.indexQA].select.some(i=>i.bg)){
        t.setData({timeQA:10,indexQA:++d.indexQA})
      }else {
        t.setData({timeQA:10, indexQA:0, rewardQA:true})
      }
      d.rewardQA && clearInterval(d.timeOutQA);
    },1000)
  },

  setABCD(e){
    let t = this,d=t.data;
    let idx = e.currentTarget.dataset.idx;
    let item = d.listQA[d.indexQA];
    let index = item.correct_answer-1;

    clearTimeout(d.timeOutQA);
    if(idx == index ){ //选对了
      item.select[idx].bg = '#57E46B';
      app.request({
        url:getApp().api.siteinfo.apiroot+'live/setqa',
        data:{
          group_id:item.group_id,question_id:item.question_id,
          answer:item.correct_answer,liveId:d.parmas.id,
          storeId:app.api.siteinfo.acid
        }})
    }else {
      item.select[idx].bg = '#F45742';
      item.select[index].bg = '#57E46B';
    }
    t.setData({listQA:d.listQA})
    setTimeout(()=>{
      d.listQA.length-1>d.indexQA && idx == index?
          t.setData({timeQA:10, indexQA:++d.indexQA},t.startQA) :
          t.setData({timeQA:10, indexQA:0, rewardQA:true,getQA:idx == index });
    },1500)
  },

  hideQA(){
    this.setData({showQA:'',listQA:[],indexQA:0, timeQA:10,rewardQA:false,getQA:false})
  },

  inputPwds(e){this.setData({txtPwds:e.detail.value})},
  /*
  * 直播密码模式：验证密码
  */
  typesPswSubmit(e){
    let t=this, d=t.data;
    if (d.txtPwds == '') {
      wx.showToast({icon:'none',title:'请输入邀请码'})
      return
    }
    app.request({
      url: getApp().api.siteinfo.apiroot+'live/checkInvitePwd',
      data:{
        hosId: app.api.siteinfo.hosId2,
        liveId:d.parmas.id,
        invitePwd:d.txtPwds
      },
      success(res){
        if(res.resultcode == 1){
          t.setData({
            height:0
          })
          t.setInitPage(t,d.parmas,d.token);
        }else{
          wx.hideLoading()
          wx.showToast({icon:'none',title:'邀请码错误'})
        }
      }
    })
  },



  catchtap(){},
  getLiveState(e){
    //console.log('直播状态',e.detail.code)
  },

  // 签到
  setCheckin(){
    let t=this, d=t.data;
    app.request({
            url: getApp().api.siteinfo.apiroot + "live/signuser",
            data:{
              hosId:app.api.siteinfo.hosId2,
              liveId:d.parmas.id,
              access_token:wx.getStorageSync('ACCESS_TOKEN')
            },
            success(e){
              e = e.data;
              console.log(e)
              wx.hideLoading()
              wx.showToast({icon:'none',title:e.msg})
              if(d.signup_mode == 1){
                t.setData({sign_status:1})
              }
              if(d.signup_mode == 2){
                t.setSign(0);
              }
            }
          })
  },

  // 弹出奖励模式的签到信息
  setSign(types = 1){
    let t=this, d=t.data;
    app.request({
            url: getApp().api.siteinfo.apiroot + "live/signCheck",
            data:{
              hosId:app.api.siteinfo.hosId2,
              liveId:d.parmas.id,
              access_token:wx.getStorageSync('ACCESS_TOKEN')
            },
            success(e){
              e = e.data;
              //console.log(e)
              types && wx.hideLoading()
              let sharelist = [];
              for (var i = 0; i < e.type2maxnum; i++)
              {
                if(e.shareData){
                  sharelist[i] = i < e.shareData.length ? e.shareData[i].shareAvatarUrl : '';
                }else{
                  sharelist[i] = '';
                }
              }
              if(e.sign_rule.length > 0){
                e.sign_rule = e.sign_rule.replace(/\\t/g,'\n')
              }
              t.setData({
                signData:e,
                shareData:sharelist,
                showCheckin:true,
              })
            }
          })
  },
  delSign(){this.setData({showCheckin:false})},

  // 领取好友签到奖励
  friendCheckin(){
    let t=this, d=t.data;
    app.request({
      url: getApp().api.siteinfo.apiroot + "live/signReward",
      data:{
        hosId:app.api.siteinfo.hosId2,
        liveId:d.parmas.id,
        access_token:wx.getStorageSync('ACCESS_TOKEN')
      },
      success(e){
        e = e.data;
        //console.log(e)
        wx.hideLoading()
        wx.showToast({icon:'none',title:e.message})
        t.setSign(0);
      }
    })
  },

  //签到规则说明
  checkin_rule(){this.setData({showRule:true})},
  delRule(){this.setData({showRule:false})},


  /**
     * 判断邀约权限
     */
    inviteShare(action) {
      const _this = this, d = this.data
      const token = wx.getStorageSync('ACCESS_TOKEN')
      app.request({
          url: getApp().api.siteinfo.apiroot + "inviteShare/notify",
          data: {
              hosId: app.api.siteinfo.hosId2,
              access_token: token,
              action: action,
              userId: d.userInfo.id,
              liveId: d.options.id
          },
          success(res) {
              console.log('判断邀约权限', res.data)
          }
      })
  },
  /**
   * 检查红包条件个数是否不止一个
   */
  checkHongbaoCount() {
      let _this = this
      if (this.data.HongBaoCount > 0) {
          setTimeout(() => {
              _this.setData({
                  isShowHongBao: true,
              })
          }, 1300)
      }
  },
  /**
   * 显示红包窗口
   */
  bindShowHbModal(){
      let _this = this
      wx.request({
          url: _this.data.liveData.invite_hb_url,
          success(res) {
              console.log('红包列表',res.data)
              _this.setData({
                  showHbModal:true,
                  hb_list: res.data.data
              })
          },

      })
  },
  /**
   * 关闭红包弹窗
   */
  closeHbModal(){this.setData({showHbModal:false})},
    /**
   * 关闭倒计时
   */
  closeCountdown(){this.setData({isShowCountdown:false})},
  /**
   * 通过IM弹出红包领取
   */
  getHongBaoByIM(){
     let _this = this, d = this.data
     let hbId = null
     if(_this.data.hbId_arr.length>0){
          hbId = _this.data.hbId_arr[0]
     }
      _this.getHongBao('IM','inviteShare/referee_push_hb',hbId)
  },
  getHongBao(type,url,hbId = null,index = null){
      let _this = this, d = this.data
      if (_this.data.referee_push_hb_disable) {
          return
      }
      wx.showLoading({ title: '加载中...' })
      _this.data.referee_push_hb_disable = true
      const access_token = wx.getStorageSync('ACCESS_TOKEN')
      let params = {
          hosId: app.api.siteinfo.hosId2,
          access_token: access_token,
          userId: d.userInfo.id,
          liveId: d.options.id,
      }
      type!==null && ( params.hbId = hbId)
      console.log('params',params)
      app.request({
          url: getApp().api.siteinfo.apiroot + url,
          data: params,
          success(res) {
              const data = res.data
              wx.showToast({
                  icon: 'none',
                  title: data.msg,
                  duration: 1500,
                  success() {
                      if(type=='list'){
                          setTimeout(() => {
                              _this.setData({
                                  isShowHongBao: false,
                                  referee_push_hb_disable: false,
                                  [`hb_list[${index}].status`]: 1
                              })
                          }, 1500)
                      }else{
                          setTimeout(() => {
                              _this.data.hbId_arr.splice(0,1)
                              _this.setData({
                                  isShowHongBao: false,
                                  referee_push_hb_disable: false,
                                  HongBaoCount: _this.data.HongBaoCount - 1,
                                  hbId_arr:_this.data.hbId_arr
                              })
                              _this.checkHongbaoCount()
                          }, 1500)
                      }
                  }
              })
          },
          complete(){
              wx.hideLoading()
          }
      })
  },
  /**
   * 通过列表领取邀约红包
   */
  getHongBaoByList(e) {
      const hbId =e.currentTarget.dataset.id
      const index =e.currentTarget.dataset.index
      console.log('红包id、索引',hbId,index)
      let _this = this, d = this.data
      _this.getHongBao('list','inviteShare/referee_push_hb',hbId,index)
  },
  /**
   * 滚动公告
   */
  scrollNotice: function () {
    var t = this,windowWidth = wx.getSystemInfoSync().windowWidth;
    if (t.data.noticelength > windowWidth) {
      var interval = setInterval(function () {
        var crentleft = t.data.marqueeDistance;
        if (crentleft < t.data.noticelength+wx.getSystemInfoSync().windowWidth*2) {//判断是否滚动到最大宽度
          t.setData({
            marqueeDistance: crentleft + t.data.marqueePace
          })
        }
        else {
          t.setData({
            marqueeDistance: 0 // 直接重新滚动
          });
          clearInterval(interval);
          t.scrollNotice();
        }
      }, t.data.noticeinterval);
    }
  },
  /*noticeShow: function () {
    let t = this
    wx.setStorageSync('noticeShow', !t.data.noticeShow)
    t.setData({noticeShow:wx.getStorageSync('noticeShow')})
  },*

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let d = this.data,l= d.liveData;
    if (res.from === 'button') {
      return {
        title:'直播签到领大奖',
        path:'/cheng/pages/live1/live1?id='+d.parmas.id+'&oriToken='+d.token+'&referee_id='+wx.getStorageSync('PARENT_ID'),
        imageUrl:l.share_img
      }      
    } else if (res.from === 'menu'){
      return {
        title:l.room_name,
        path:'/cheng/pages/live1/live1?id='+d.parmas.id+'&oriToken='+d.token+'&referee_id='+wx.getStorageSync('PARENT_ID'),
        imageUrl:l.share_img
      }
    }
  }
})